package Testing.Projektarbete;

import java.io.*;
import java.net.*;
import java.util.ArrayList;


public class MultipleThreads implements Runnable{
	private Socket client;
	private DataInputStream in;
    private DataOutputStream out;   
    private ArrayList<Users> userList;

	public class Users {
        String userName;
        String userPassword;
        
        public Users(String id, String pw){
            userName = id;
            userPassword = pw;
        }
    }
		
	private void newList() throws IOException {
        userList.clear();
        BufferedReader in = new BufferedReader(new FileReader("database.txt"));
        String line;
        int i = 0;
        
        while((line = in.readLine())!=null)
        {   
            String[] str = line.split(" ");
            Users users = new Users(str[0],str[1]);
            userList.add(i,users);
            i++;
        }
    }
	
	public MultipleThreads(Socket client){
		this.client = client;
	}
	
	public void run(){
		try {
        	in=new DataInputStream(client.getInputStream());
        	out=new DataOutputStream(client.getOutputStream());
        	
        	while(true){
        		if (in.readUTF().equals("check"))
        		{
        			String userName = in.readUTF();
        			String userPassword = in.readUTF();
        	
        			if(checkName(userName)){           	
        				if(checkPassword(userName,userPassword)){
        					out.writeUTF("LOGIN");
        				}else{
        					out.writeUTF("WRONG_PW");
        				}
        			}else{
            				out.writeUTF("NO_USER_FOUND");
        			}
        		}
        	}
        }catch (IOException e){
        }
	}
	
	private boolean checkName(String userName) throws IOException {
		userList = new ArrayList<Users>();
        newList();
        
        int i = 0;
        
        while (i < userList.size()){
            Users users = userList.get(i);
            if(users.userName.equals(userName)){
                return true;
            }
            i++;
        }
        return false;
	}

	private boolean checkPassword(String id, String pw) throws IOException {
        userList = new ArrayList<Users>();
        newList();
        
        int i = 0;
        
        while (i < userList.size()){
            Users users = userList.get(i);
            if(users.userName.equals(id) && users.userPassword.equals(pw)){
                return true;
            }
            i++;
        }
        return false;
    }
	 
}
